<?php
// 连接，选择数据库
$link = mysql_connect('localhost', 'root', 'root')
    or die('Could not connect: ' . mysql_error());
mysql_select_db('test') or die('Could not select database');
 mysql_query('set names utf8');
// 执行 SQL 查询
$query = 'SELECT id,parent_id,name FROM menu';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$list = array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
    $list[] = $row;    
	echo $row['id'].'&nbsp;&nbsp;'.$row['parent_id'].'&nbsp;&nbsp;'.$row['name'].'<br>';
}
echo '总共有'.count($list).'个<BR>';
//$list = 
//echo '<pre>';
#echo_arr($list);
$newlist = array();
//print_r($newlist);
function taxonomy($list,&$newlist,$pid=0,$lv=0){
    foreach($list as $key=>$val){
        if( $val['parent_id'] == $pid){
			$val['lv'] = $lv;
			$newlist[] = $val;
			#$i++;
			#$lv++;
			taxonomy($list,$newlist,$val['id'],$lv+1);
			#$lv--;
		}
	}
}
function formatArr($arr,$pre='-'){
	foreach($arr as &$val){
		$val['name'] = str_repeat($pre,$val['lv']).$val['name'];
	}
	return $arr;
}

taxonomy($list,$newlist,0,0);
//$newlist = formatArr
echo_arr($newlist);
foreach($newlist as $val){
	echo str_repeat('-',$val['lv']).$val['name'].'<br/>';
}
function echo_arr($arr){
	foreach($arr as $val){
		print_r($val);
		echo '<br/>';
	}
}

?>
